package top.xiangqifu.springboot2.user.service.impl;

import com.github.javafaker.Faker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.xiangqifu.springboot2.user.base.BaseResult;
import top.xiangqifu.springboot2.user.dao.TbUserDAO;
import top.xiangqifu.springboot2.user.dao.TbUserInfoDAO;
import top.xiangqifu.springboot2.user.entity.TbUser;
import top.xiangqifu.springboot2.user.entity.TbUserInfo;
import top.xiangqifu.springboot2.user.service.AuthService;
import top.xiangqifu.springboot2.user.service.AutoDataService;
import top.xiangqifu.springboot2.user.utils.PinyinUtil;


import java.util.Locale;
import java.util.Random;

@Service
@RequiredArgsConstructor
@Slf4j
public class AutoDataServiceImpl implements AutoDataService {
    private final TbUserDAO tbUserDAO;
    private final TbUserInfoDAO tbUserInfoDAO;
    private final PinyinUtil pinyinUtil;
    private final AuthService authService;

    @Override
    public int makeUser() {
        Faker faker = new Faker(Locale.CHINA);
        int count = 0;
        Random random = new Random();
        int total = random.nextInt(AutoDataService.MAX_USER- AutoDataService.MIN_USER+1)+ AutoDataService.MIN_USER;
        for (int i = 0; i < total; i++) {
            // 随机数据
            String nickname = faker.name().fullName();
            String username = pinyinUtil.getPinYin(nickname);
            String phone = faker.phoneNumber().cellPhone();
            String email = faker.internet().emailAddress(username);
            // 注册用户
            TbUser user = new TbUser();
            user.setUsername(username);
            user.setPassword("user-pwd");
            BaseResult result = authService.reg(user);
            if (!result.isSuccess()) {
                continue;
            }
            log.debug("随机用户：{}", user);
            // 修改附加信息
            TbUserInfo tbUserInfo = new TbUserInfo();
            tbUserInfo.setUid(user.getUid());
            tbUserInfo.setNickname(nickname);
            tbUserInfo.setEmail(email);
            tbUserInfo.setPhone(phone);
            tbUserInfoDAO.updateById(tbUserInfo);
            log.debug("随机用户附加信息：{}", tbUserInfo);
            count++;
        }
        return count;
    }

}
